﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using System.IO;

namespace TestXNA3.Resources
{
    public class TextureResource : Resource
    {
        private struct TextureDesc
        {
            public string TextureName;
            public ResourceManager.ManagedResource<Texture> Texture;
        };
        private static List<TextureDesc> _cachedTextures = null;

        public Texture Texture
        {
            get { _texture.LastTimeUsed = GameStartup.StaticGameStartup.GameInfo.TimeSeconds; return _texture.Active; }
        }

        private ResourceManager.ManagedResource<Texture> _texture = null;
        private string _textureName;
        public string TextureName
        {
            get { return _textureName; }
            set { _textureName = value; _texture = SetTexture(_textureName); }
        }

        public TextureResource(string textureName)
        {
            _textureName = textureName;
            if (_cachedTextures == null)
            {
                _cachedTextures = new List<TextureDesc>();
            }
            _texture = SetTexture(textureName);
        }

        private ResourceManager.ManagedResource<Texture> SetTexture(string textureName)
        {
            textureName = TestConfig.ContentPath + "Textures/" + textureName;
            foreach (TextureDesc desc in _cachedTextures)
            {
                if (desc.TextureName == textureName)
                {
                    return desc.Texture;
                }
            }

            ResourceManager.ManagedResource<Texture> texture = null;
            try
            {
                texture = GameStartup.ContentManager.LoadManagedTexture(textureName);
            }
            catch
            {
                Logger.Print("Can't find texture " + textureName);
            }
            
            if (texture != null)
            {
                TextureDesc desc;
                desc.Texture = texture;
                desc.TextureName = textureName;
                _cachedTextures.Add(desc);
            }
            return texture;
        }

        public override string ToString()
        {
            return _textureName;
        }
    }
}
